/**
 * 泛娱区块链 - 我的
 * http://menger.me
 * @Zaric
 */

'use strict';

import React, {Component} from 'react'
import {ImageBackground, RefreshControl, ScrollView, StyleSheet, Text, TouchableOpacity, View} from 'react-native'
import Theme from '../../config/themes/Theme';
import MineHintView from '../../component/mine/MineHintView';
import {ListRow} from 'teaset'
import {inject, observer} from 'mobx-react';
import ImageView from '../../component/common/ImageView';

@inject('loginStore', 'taskStore')
@observer
export default class Mine extends Component {

    constructor(props) {
        super(props);
        const {loginStore} = this.props;
        const userInfo = loginStore.getUserInfo;
        this.state = {
            hintData: [
                {number: userInfo.collect_count ? userInfo.collect_count : 0, text: '收藏', key: 'collection'},
                {},
                {number: userInfo.focus_count ? userInfo.focus_count : 0, text: '关注', key: 'follow'},
                {},
                {number: userInfo.followers_count ? userInfo.followers_count : 0, text: '粉丝', key: 'fans'},
            ],
            refreshing: false,
        };
        this.dataSource = [
            {key: 'money', icon: Images.icon_money, title: '我的资产', show: true},
            {key: 'me', icon: Images.icon_about_me, title: '与我有关', show: true},
            {key: 'send', icon: Images.icon_mine_send, title: '我的发布', show: true},
            {key: 'point', icon: Images.icon_point_market, title: '积分商城', show: true},
            {key: 'feed', icon: Images.icon_feed_back, title: '意见反馈', show: true},
            {key: 'friends', icon: Images.icon_invite_friends, title: '邀请好友', show: true},
            {key: 'our', icon: Images.icon_about_mine, title: '关于我们', show: true},
        ]
    }

    componentDidMount() {

    }

    componentWillUnmount() {
        this.timer1 && clearTimeout(this.timer1);
    }

    requestDataSources = async () => {
        let {hintData} = this.state;
        let hintDataTemp = hintData.slice();
        let {getUserData, getUserInfo} = this.props.loginStore;
        let result = await getUserData(getUserInfo.user_id);
        if (result.code === StatusCode.SUCCESS_CODE) {
            hintDataTemp[0].number = result.data.collect_count;
            hintDataTemp[2].number = result.data.focus_count;
            hintDataTemp[4].number = result.data.followers_count;
            this.setState({
                hintData: hintDataTemp,
            });
        }
    };

    onRefresh = () => {
        this.setState({refreshing: true});
        this.requestDataSources();
        this.timer1 = setTimeout(() => {
            this.setState({refreshing: false});
        }, 1000);
    };

    _onPressItem = (key) => {
        const {loginStore} = this.props;
        switch (key) {
            case 'money':
                if (!__DEV__ && global.secretKey === '') {
                    RouterHelper.navigate('登录', 'Login');
                    break
                }
                RouterHelper.navigate('我的资产', 'MyAssets')
                break;
            case 'me':
                if (!__DEV__ && global.secretKey === '') {
                    RouterHelper.navigate('登录', 'Login');
                    break
                }
                RouterHelper.navigate('与我相关', 'AboutMe');
                break;
            case 'send':
                if (!__DEV__ && global.secretKey === '') {
                    RouterHelper.navigate('登录', 'Login');
                    break
                }
                RouterHelper.navigate('我的发布', 'MyPublish');
                break;
            case 'point': //积分商城
                if (!__DEV__ && global.secretKey === '') {
                    RouterHelper.navigate('登录', 'Login');
                    break
                }
                RouterHelper.navigate('积分商城', 'PointShopping');
                break;
            case 'feed':
                RouterHelper.navigate('意见反馈', 'FeedBack');
                break;
            case 'friends':
                if (!__DEV__ && global.secretKey === '') {
                    RouterHelper.navigate('登录', 'Login');
                    break
                }
                this._onPressInviteFriends();
                break;
            case 'our':
                RouterHelper.navigate('关于我们', 'AboutOur');
                break;
            default:
                break;
        }
    };

    //邀请好友
    _onPressInviteFriends = async () => {
        const {loginStore, taskStore} = this.props;
        let nickname = loginStore.getUserInfo.user_nickname ? loginStore.getUserInfo.user_nickname : '';
        ActionsManager.showShareModule({
            type: 'link',
            title: '北链泛娱',
            text: `你的好友${nickname}邀请你使用北链泛娱`,
            url: ServicesApi.DOWNLOAD_HOST,
            imageUrl: ServicesApi.ICON_APP,
        });
        await taskStore.saveTask('invitation')
    };

    //设置
    _onPressSetting = () => {
        RouterHelper.navigate('设置', 'Settings')
    };

    //用户头部信息点击事件
    _onPressUserInfo = () => {
        if (global.secretKey === '') {
            RouterHelper.navigate('登录', 'Login');
        } else {
            RouterHelper.navigate('个人资料修改', 'EditInfo');

        }
    };

    //签到
    _onPressSign = async () => {
        const {taskStore, loginStore} = this.props;
        let {userInfo} = loginStore;
        if (global.secretKey === '') {
            RouterHelper.navigate('登录', 'Login');
            return;
        }
        if (userInfo.sign_state > 0) {
            ToastManager.show('今天已经签过了哦~');
            return;
        }
        const result = await taskStore.saveTask('signin');
        if (result.code === StatusCode.SUCCESS_CODE) {
            this.requestDataSources();
            ToastManager.show('签到成功')
        } else if (result.code === 55000) {
            ToastManager.show('今天已经签过了哦~');
        } else {
            ToastManager.show(result.dec || 'error');
        }
    };

    _onPressHintItem = (key) => {
        if (!__DEV__ && global.secretKey === '') {
            RouterHelper.navigate('登录', 'Login');
            return;
        }
        switch (key) {
            case 'collection':
                RouterHelper.navigate('收藏', 'MyCollection', {
                    onCallBack: () => this.requestDataSources()
                });
                break;
            case 'follow':
                RouterHelper.navigate('关注的作者', 'MyFollowFans', {
                    type: Constants.WATCH_TYPE,
                    onCallBack: () => this.requestDataSources()
                });
                break;
            case 'fans':
                RouterHelper.navigate('我的粉丝', 'MyFollowFans', {
                    type: Constants.FANS_TYPE,
                    onCallBack: () => this.requestDataSources()
                });
                break;
            default:
                break;
        }

    };

    render() {
        const {hintData, refreshing} = this.state;
        const {loginStore} = this.props;
        let {userInfo} = loginStore;
        const imgHead = loginStore.getUserInfo.user_img;
        const width = SCREEN_WIDTH;
        const height = SCREEN_WIDTH * 0.597;
        return (
            <View style={styles.container}>

                <ScrollView
                    style={styles.scroll}
                    keyboardShouldPersistTaps={'handled'}
                    refreshControl={
                        <RefreshControl
                            title='Loading...'
                            refreshing={refreshing}
                            onRefresh={this.onRefresh}
                            tintColor="#0398ff"
                            colors={['#0398ff']}
                            progressBackgroundColor="#fff"
                        />
                    }
                >
                    <ImageBackground style={[styles.topView, {width, height}]} source={Images.img_bg_mine}>
                        <TouchableOpacity style={styles.setting} onPress={this._onPressSetting}>
                            <ImageView style={styles.settingImage} source={Images.icon_setting}/>
                        </TouchableOpacity>
                        <View style={styles.userView}>
                            <TouchableOpacity style={styles.flexCenter} onPress={this._onPressUserInfo}>
                                <View style={styles.flexCenter}>
                                    <ImageView
                                        resizeMode={'cover'}
                                        style={styles.avatarImage}
                                        source={imgHead ? {uri: imgHead} : Images.icon_default_avatar}
                                    />
                                    <View style={styles.userinfo}>
                                        <Text
                                            style={styles.nickname}>{loginStore.userInfo.user_nickname ? loginStore.userInfo.user_nickname : '没有昵称'}</Text>
                                        <Text
                                            style={styles.signName}>{loginStore.userInfo.user_remark ? loginStore.userInfo.user_remark : '还没有签名哦~'}</Text>
                                    </View>
                                </View>
                            </TouchableOpacity>
                            <TouchableOpacity style={styles.signView} onPress={this._onPressSign}>
                                <View style={styles.signView}>
                                    <ImageView style={styles.signImage} source={Images.icon_gift}/>
                                    <Text style={styles.sign}>{userInfo.sign_state > 0 ? '已签到' : '签到'}</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                        <MineHintView
                            data={hintData}
                            onPressItem={this._onPressHintItem}
                        />
                    </ImageBackground>
                    {this.dataSource.map((item, index) => {
                        if (!item.show) {
                            return null
                        }
                        return (
                            <ListRow
                                key={`${index}`}
                                onPress={() => this._onPressItem(item.key)}
                                style={styles.listRow}
                                icon={item.icon}
                                iconStyle={styles.listIconStyle}
                                title={item.title}
                            />
                        )
                    })}
                </ScrollView>

            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    scroll: {
        flex: 1,
    },
    topView: {
        height: 224,
        width: Theme.screenWidth,
    },
    userView: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 74,
        justifyContent: 'space-between'
    },
    flexCenter: {
        flexDirection: 'row',
        alignItems: 'center'
    },
    setting: {
        top: 35,
        right: 15,
        width: 40,
        height: 40,
        position: 'absolute',
        alignItems: 'flex-end',
    },
    settingImage: {
        width: 19,
        height: 20,

    },
    avatarImage: {
        width: 76,
        height: 76,
        borderRadius: 76 / 2,
        marginLeft: 39,
    },
    userinfo: {
        marginLeft: 13,
    },
    nickname: {
        fontSize: FontSize(18),
        color: "#ffffff"
    },
    signName: {
        fontSize: FontSize(12),
        color: "#ffffff",
        marginTop: 6,
    },
    signView: {
        flexDirection: 'row',
        borderBottomLeftRadius: 30,
        borderTopLeftRadius: 30,
        backgroundColor: '#4a90e2',
        paddingLeft: 12,
        paddingRight: 17,
        alignItems: 'center',
        paddingVertical: 6,
    },
    signImage: {
        width: 13,
        height: 15,
    },
    sign: {
        fontSize: FontSize(12),
        color: '#fff',
        marginLeft: 4,
    },
    listRow: {
        paddingLeft: 15,
        paddingRight: 15,
        paddingTop: 15,
        paddingBottom: 15,
    },
    listIconStyle: {
        width: 18,
        height: 18,
        resizeMode: 'contain',
    },
});